<template>
  <div class="app-container">
    <div class="chat-box">
      <div v-for="(msg, index) in messages" :key="index" class="message">
        <div class="user-msg"><strong>你：</strong>{{ msg.question }}</div>
        <div class="ai-msg"><strong>AI：</strong>{{ msg.answer }}</div>
      </div>
    </div>

    <div class="input-box">
      <el-input
        type="textarea"
        :rows="3"
        v-model="input"
        placeholder="请输入你的问题"
      />
      <el-button type="primary" @click="sendMessage" style="margin-top: 10px">发送</el-button>
    </div>
  </div>
</template>

<script>
import { chatWithAI } from '@/api/ai'

export default {
  name: 'AIChat',
  data() {
    return {
      input: '',
      messages: [], // 存储对话历史
      conversationId: null // 服务器返回的上下文ID
    }
  },
  methods: {
    async sendMessage() {
      const question = this.input.trim()
      if (!question) {
        this.$message.warning('请输入问题')
        return
      }

      // 先清空输入框 & 添加问题到 messages
      this.input = ''
      const tempMsg = { question, answer: 'AI思考中...' }
      this.messages.push(tempMsg)

      try {
        const res = await chatWithAI({ question, conversationId: this.conversationId })

        // 替换当前 message 中的 AI 回答
        tempMsg.answer = res.data.data.answer

        // 更新 conversationId，保持上下文
        this.conversationId = res.data.data.conversationId
      } catch (err) {
        tempMsg.answer = 'AI回答失败: ' + (err.message || '未知错误')
      }
    }
  }
}
</script>

<style scoped>
.chat-box {
  background: #f9f9f9;
  padding: 20px;
  border-radius: 6px;
  max-height: 500px;
  overflow-y: auto;
  margin-bottom: 20px;
  border: 1px solid #e0e0e0;
}
.message {
  margin-bottom: 15px;
}
.user-msg {
  margin-bottom: 5px;
}
.ai-msg {
  background: #f4f4f4;
  padding: 10px;
  border-left: 4px solid #409EFF;
  border-radius: 4px;
}
.input-box {
  background: #fff;
  padding: 10px;
  border-radius: 6px;
  border: 1px solid #e0e0e0;
}
</style>
